package me.zhanshi123.advancedcleaner.item;

import me.zhanshi123.advancedcleaner.Main;
import org.bukkit.entity.Item;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Method;

public class ScriptManager {
    private ScriptEngine nashorn;
    private File file;

    public ScriptManager() {
        String javaVersion = System.getProperty("java.specification.version");
        switch (javaVersion) {
            case "1.8":
                try {
                    Class<?> factoryClass = Class.forName("jdk.nashorn.api.scripting.NashornScriptEngineFactory");
                    Object factoryObject = factoryClass.getConstructor().newInstance();
                    Method getScriptEngineMethod = factoryClass.getMethod("getScriptEngine", ClassLoader.class);
                    nashorn = (ScriptEngine) getScriptEngineMethod.invoke(factoryObject, Main.getInstance().getClass().getClassLoader());
                } catch (Exception e) {
                    Main.getInstance().getLogger().warning("Cannot load JavaScript engine");
                    e.printStackTrace();
                }
                break;
            default:
                try {
                    nashorn = new ScriptEngineManager(Main.getInstance().getClass().getClassLoader()).getEngineByName("nashorn");
                    if (nashorn == null) {
                        Main.getInstance().getLogger().warning("Cannot load JavaScript engine");
                        return;
                    }
                } catch (Exception e) {
                    Main.getInstance().getLogger().warning("Cannot load JavaScript engine");
                    e.printStackTrace();
                }
                break;
        }
        if (nashorn == null) {
            return;
        }
        file = new File(Main.getInstance().getDataFolder(), "script.js");
        if (!file.exists()) {
            Main.getInstance().saveResource("script.js", false);
        }
        try {
            nashorn.eval(new FileReader(file));
        } catch (ScriptException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean isNeedToClean(Item item) {
        try {
            if (item == null) {
                return true;
            }
            Invocable invocable = (Invocable) nashorn;
            Object result = invocable.invokeFunction("isNeedToClean", item);
            return (boolean) result;
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
            Main.getInstance().getLogger().warning("JavaScript resolve error! Please reset script.js");
        }
        return true;
    }

}
